from .StrategyHandler import Strategy
from ..deal_handler.DemoDealHandler import DemoDealHandler


class MovingAverageCrossStrategy(Strategy):
    """
    用来进行基本的移动平均跨越测录的实现，这个策略有一组短期和长期的简单移动平均值。
    默认的短期/长期的窗口分别是100天和400天。
    UPDATE `stock`.`account` SET `total_funds` = 10000, `total_market_value` = 0, `total_available_funds` = 10000, `remaining_available_funds` = 10000 WHERE `id` = 1;

TRUNCATE TABLE `order`;

TRUNCATE TABLE position;

TRUNCATE TABLE position_record;


    """

    def __init__(self, stock_code, short_window=10, long_window=20):
        self.stock_code = stock_code
        self.short_window = short_window
        self.long_window = long_window

        self.position = self._calculate_position()

    def _calculate_position(self):
        return None

    def indicator_pretreatment(self, pd_data):
        '''
        指标预处理
        '''
        pd_data['ma_short'] = pd_data['close'].rolling(self.short_window).mean()
        pd_data['ma_long'] = pd_data['close'].rolling(self.long_window).mean()

        # 金叉
        pd_data.loc[(pd_data['ma_short'] >= pd_data['ma_long']) & (
                pd_data['ma_short'].shift(1) < pd_data['ma_long'].shift(1)), 'ma_signal'] = 1
        # 死叉
        pd_data.loc[(pd_data['ma_short'] <= pd_data['ma_long']) & (
                pd_data['ma_short'].shift(1) > pd_data['ma_long'].shift(1)), 'ma_signal'] = -1

        pd_data['ma_signal'].fillna(value=0, inplace=True)

    def calculate_signals(self, pd_data):
        """
        基于MAC SMA生成一组新的信号，进入市场的标志就是短期的移动平均超过
        长期的移动平均。
        """
        self.indicator_pretreatment(pd_data)
        stock_data = pd_data[['close', 'ma_signal','close','open']]

        for index, row in stock_data.iterrows():
            ma_signal = row.get('ma_signal')
            price=row.get('close')
            if ma_signal == 0:
                continue
            if ma_signal == -1:
                # 卖出信号
                print("卖出------" + str(index))
                DemoDealHandler(self.stock_code).sell(price[0])

            elif ma_signal == 1:
                print("买入-----" + str(index))
                DemoDealHandler(self.stock_code).buy(price[0])
